package com.example.java_gobang.api;
import com.example.java_gobang.game.MatchRequest;
import com.example.java_gobang.game.MatchResponse;
import com.example.java_gobang.game.Matcher;
import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MatchAPI extends TextWebSocketHandler {

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    OnlineUserManager onlineUserManager;

    @Autowired
    Matcher matcher;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            //用户上线
            User user = (User) session.getAttributes().get("user");
            //防止用户多开
            WebSocketSession webSocketSession = onlineUserManager.getSessionByHall(user.getUserId());
            if(webSocketSession != null || onlineUserManager.getSessionByRoom(user.getUserId()) != null){
                System.out.println("当前用户已登录");
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("当前用户已登录");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                return;
            }
            //设置上线状态
            onlineUserManager.enterGameHall(user.getUserId(), session);
            System.out.println("玩家" +user.getUsername() + "已上线大厅");
        }catch (NullPointerException e){
            e.printStackTrace();
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //校验用户登录
        User user = (User) session.getAttributes().get("user");
        if(user == null){
            System.out.println("用户未登录");
            return;
        }
        MatchRequest request = objectMapper.readValue(message.getPayload(), MatchRequest.class);
        MatchResponse response = new MatchResponse();
        //处理请求
        if("startMatch".equals(request.getMessage())){
            response.setOk(true);
            response.setMessage("startMatch");
            matcher.add(user);
        }else if("stopMatch".equals(request.getMessage())){
            response.setOk(true);
            response.setMessage("stopMatch");
            matcher.remove(user);
        }else {
            response.setOk(false);
            response.setReason("异常响应");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            //用户下线
            User user = (User) session.getAttributes().get("user");
            onlineUserManager.exitGameHall(user.getUserId());
            WebSocketSession webSocketSession = onlineUserManager.getSessionByHall(user.getUserId());
            if(webSocketSession == session) {
                onlineUserManager.exitGameHall(user.getUserId());
                System.out.println("玩家" +user.getUsername() + "已下线");
            }

        }catch (NullPointerException e){
            e.printStackTrace();
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            //用户下线
            User user = (User) session.getAttributes().get("user");
            //防止用户多开误删
            WebSocketSession webSocketSession = onlineUserManager.getSessionByHall(user.getUserId());
            if(webSocketSession == session) {
                onlineUserManager.exitGameHall(user.getUserId());
                System.out.println("玩家" +user.getUsername() + "已下线");
            }

        }catch (NullPointerException e){
            e.printStackTrace();
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }
}
